package org.book.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.book.dao.BookBean;
import org.book.service.BookService;


/**
 * Servlet implementation class BooksServlet
 */
@WebServlet("/BooksServlet")
public class BooksServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public BooksServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");


		String textName = request.getParameter("textName");

		Object obj = request.getParameter("pageCurrent");
		//修改删除之后保持页码
		Object obj2 = request.getAttribute("pageCurrent2");

		BookService bookService = new BookService();

		List<BookBean> list = new ArrayList<>();

		int pageCurrent = 1;

		//页码
		if(obj!=null) {
			pageCurrent = Integer.parseInt(obj.toString());
		}
		//页码
		if(obj2!=null) {
			pageCurrent = Integer.parseInt(obj2.toString());
		}

		//搜索
		if(textName!=null) {
			list = bookService.getLike(textName);
		}
		//显示
		else {
			list = bookService.getList(pageCurrent,10);
		}

		request.setAttribute("list", list);

		request.setAttribute("pageCurrent", pageCurrent);

		request.setAttribute("count", bookService.getCount());

		//借阅跳转判断
		String user = request.getParameter("user_id");
		if(user!=null) {
			int user_id = Integer.parseInt(user);
			request.getSession().setAttribute("user_id", user_id);
			//30秒后失效
			request.getSession().setMaxInactiveInterval(10);
		}

		request.getRequestDispatcher("pages/home/home.jsp").forward(request, response);



	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
